<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :title="userParams.id ? '修改用户' : '添加用户'"
      @cancel="visible = false"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="userParams" ref="formRef">
        <a-form-item
          field="username"
          label="用户名"
          :rules="[{ required: true, message: 'username is required' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="userParams.username"
            placeholder="请输入用户名"
          />
        </a-form-item>
        <a-form-item
          field="email"
          label="邮箱地址"
          :rules="[
            {
              required: true,
              type: 'email',
            },
          ]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="userParams.email"
            placeholder="请输入邮箱地址"
          />
        </a-form-item>
        <a-form-item
          v-if="!userParams.id"
          field="password"
          label="用户密码"
          :rules="[
            {
              required: true,
              message: 'password is required',
            },
          ]"
          validate-trigger="blur"
        >
          <a-input-password
            style="width: 350px"
            v-model="userParams.password"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item
          v-if="!userParams.id"
          field="password2"
          label="确认密码"
          validate-trigger="blur"
          :rules="[
            { required: true, message: '确认密码不能为空' },
            { validator: validatePassCheck, required: true },
          ]"
        >
          <a-input-password
            style="width: 350px"
            v-model="userParams.password2"
            placeholder="请输入确认密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-card>
      <a-space size="medium">
        <a-input-search
          :style="{ width: '280px' }"
          placeholder="请输入用户名"
          search-button
          @search="getUserListByName"
          v-model="keyword"
        />
        <a-button @click="openVisible" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>添加用户</template>
        </a-button>
        <a-popconfirm content="你确定要删除这些用户吗?" @ok="batchDelete">
          <a-button type="primary" status="danger">
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-popconfirm>
      </a-space>
    </a-card>
    <a-card>
      <a-table
        :data="userInfoArr"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="id"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectUser"
      >
        <template #columns>
          <a-table-column title="用户名" data-index="username"></a-table-column>
          <a-table-column title="邮箱地址" data-index="email"></a-table-column>
          <a-table-column title="状态">
            <template #cell="{ record }">
              <a-switch
                checked-color="#14C9C9"
                :model-value="record.status === 1"
                @change="changeStatus(record)"
              />
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-button @click="editUser(record)" type="outline" size="mini">
                  <template #icon>
                    <icon-edit />
                  </template>
                  <template #default>编辑</template>
                </a-button>
                <a-popconfirm
                  @ok="deleteUser(record.id)"
                  content="你确定要删除吗?"
                >
                  <a-button size="mini" status="danger">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-pagination
        @change="getHasUserInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqAddUser,
  reqBatchDeleteUser,
  reqChangeUserStatus,
  reqDeleteUserById,
  reqUserByName,
  userInfoListPage,
} from '@/api/user'
import { Message, Notification } from '@arco-design/web-vue'
import { IconDelete, IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { nextTick, onMounted, reactive, ref } from 'vue'
let userInfoArr = ref([])
let total = ref<number>(0)
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<String>()
let selectUser = ref([])
let formRef = ref()
const visible = ref(false)
const validatePassCheck = (value: any, callback: any) => {
  if (value !== userParams.password) {
    callback('two passwords do not match')
  } else {
    callback()
  }
}
const userParams = reactive({
  id: 0,
  username: '',
  email: '',
  password: '',
  password2: '',
})

onMounted(() => {
  getHasUserInfo()
})

// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getHasUserInfo(pageNo.value)
}
// 编辑用户
const editUser = (record: any) => {
  Object.assign(userParams, record)
  visible.value = true
}
// 删除用户
const deleteUser = async (userId: number) => {
  let result: any = await reqDeleteUserById(userId)
  if (result.status === 'OK') {
    Message.success(result.message)
    getHasUserInfo(userInfoArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 通过用户名搜索
const getUserListByName = async () => {
  if (keyword.value) {
    let result: any = await reqUserByName(
      pageNo.value,
      pageSize.value,
      keyword.value,
    )
    if (result.status === 'OK') {
      userInfoArr.value = result.data.records
    }
  } else {
    getHasUserInfo()
  }
}
// 批量删除
const batchDelete = async () => {
  if (selectUser.value.length < 1) {
    Notification.warning({
      title: '删除提示',
      content: '请选择你要删除的用户!',
    })
    return
  }
  let result = await reqBatchDeleteUser(selectUser.value)
  if (result.status === 'OK') {
    Message.success(result.message)
    getHasUserInfo(pageNo.value)
  }
}
// 模态框点击确定
const handleBeforeOk = () => {
  formRef.value.validate(async (r: any, _Record: any) => {
    if (r === undefined) {
      // 发送请求
      let result = await reqAddUser(userParams)
      if (result.status === 'OK') {
        Message.success(result.message)
        visible.value = false
        getHasUserInfo();
      } else {
        Message.error(result.message)
      }
    }
  })
}
// 打开模态框
const openVisible = () => {
  Object.assign(userParams, {
    id: 0,
    username: '',
    email: '',
    password: '',
    password2: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('email')
    formRef.value.clearValidate('password')
    formRef.value.clearValidate('password2')
  })
  visible.value = true
}
// 改变状态
const changeStatus = async (userObj: any) => {
  let result = await reqChangeUserStatus(
    userObj.id,
    userObj.status === 1 ? 0 : 1,
  )

  if (result.status === 'OK') {
    getHasUserInfo(pageNo.value)
  }
}
// 获取用户数据
const getHasUserInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await userInfoListPage(pageNo.value, pageSize.value)
  if (result.status === 'OK') {
    userInfoArr.value = result.data.records
    total.value = result.data.total
  }
}
</script>

<style lang="scss" scoped></style>
